<template>
  <div class="job-info">
    <el-form
      ref="userForm"
      :model="userInfo"
      :rules="rules"
      label-width="120px"
      style="width: 500px; margin-left: 220px; margin-top: 30px"
    >
      <el-form-item label="姓名：" prop="username">
        <el-input v-model="userInfo.username" />
      </el-form-item>
      <el-form-item label="密码：" prop="password">
        <el-input v-model="userInfo.password" type="password" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="hSubmit">更新</el-button>
        <el-button type="text" @click="retrogress">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { getUserDetailById } from '@/api/user.js'
import { saveUserDetailById } from '@/api/employees.js'
export default {
  data() {
    return {
      userInfo: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '姓名不能为空', trigger: 'blur' }
        ],
        password: [{ required: true, message: '姓名不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.loadUserDetailById()
    this.userInfo['id'] = this.$route.query.id
  },
  methods: {
    // 获取用户基信息
    async loadUserDetailById() {
      try {
        const id = this.$route.query.id
        const { data } = await getUserDetailById(id)
        const { username, password } = data
        this.userInfo.username = username
        this.userInfo.password = password
      } catch (error) {
        console.log(error)
      }
    },
    // 更新保存用户信息函数
    async doEdit() {
      try {
        await saveUserDetailById(this.userInfo)
        this.$message.success('更新成功')
        // 更新数据
        this.loadUserDetailById()
      } catch (error) {
        this.$message.error('更新失败')
        console.log(error)
      }
    },
    // 更新用户信息
    hSubmit() {
      this.$refs.userForm.validate(vali => vali && this.doEdit())
    },
    // 回到上一级
    retrogress() {
      this.$router.push(
        `/employees?page=${this.$route.query.page}&size=${this.$route.query.size}`
      )
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep label {
  font-weight: 400;
}
</style>
